
const express = require('express')
const cors = require('cors')
const sqlite3 = require('sqlite3').verbose()
const path = require('path')

const app = express()
const PORT = process.env.PORT || 3001

// 中间件
app.use(cors())
app.use(express.json())
app.use(express.static(path.join(__dirname, '../dist')))

// 初始化数据库
const db = new sqlite3.Database(':memory:')

// 创建表
db.serialize(() => {
  db.run(`CREATE TABLE dolls (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL,
    price REAL NOT NULL,
    rarity TEXT NOT NULL,
    description TEXT,
    image_url TEXT,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
  )`)
  
  db.run(`CREATE TABLE raffle_participants (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL,
    phone TEXT NOT NULL,
    address TEXT NOT NULL,
    doll_id INTEGER,
    is_winner BOOLEAN DEFAULT 0,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (doll_id) REFERENCES dolls (id)
  )`)
  
  // 插入示例数据
  const stmt = db.prepare("INSERT INTO dolls (name, price, rarity, description) VALUES (?, ?, ?, ?)")
  stmt.run("青花仙子", 299, "限量", "传统青花瓷纹与现代设计的完美结合")
  stmt.run("青花舞者", 399, "珍藏", "优雅的舞姿中流淌着千年瓷韵")
  stmt.run("青花精灵", 199, "普通", "小巧精致，随身携带的东方美学")
  stmt.finalize()
})

// API路由
app.get('/api/dolls', (req, res) => {
  db.all("SELECT * FROM dolls ORDER BY id", (err, rows) => {
    if (err) {
      res.status(500).json({ error: err.message })
      return
    }
    res.json(rows)
  })
})

app.get('/api/dolls/:id', (req, res) => {
  const id = req.params.id
  db.get("SELECT * FROM dolls WHERE id = ?", [id], (err, row) => {
    if (err) {
      res.status(500).json({ error: err.message })
      return
    }
    if (!row) {
      res.status(404).json({ error: "娃娃不存在" })
      return
    }
    res.json(row)
  })
})

app.post('/api/raffle/join', (req, res) => {
  const { name, phone, address, doll_id } = req.body
  
  if (!name || !phone || !address) {
    res.status(400).json({ error: "请填写完整信息" })
    return
  }
  
  // 检查是否已经参与
  db.get("SELECT * FROM raffle_participants WHERE phone = ? AND doll_id = ?", [phone, doll_id], (err, row) => {
    if (err) {
      res.status(500).json({ error: err.message })
      return
    }
    
    if (row) {
      res.status(400).json({ error: "您已经参与过本次抽签" })
      return
    }
    
    // 插入参与者
    db.run("INSERT INTO raffle_participants (name, phone, address, doll_id) VALUES (?, ?, ?, ?)",
      [name, phone, address, doll_id], function(err) {
      if (err) {
        res.status(500).json({ error: err.message })
        return
      }
      
      // 随机决定是否中奖
      const isWinner = Math.random() < 0.035 // 3.5%中奖率
      
      if (isWinner) {
        db.run("UPDATE raffle_participants SET is_winner = 1 WHERE id = ?", [this.lastID])
      }
      
      res.json({
        success: true,
        is_winner: isWinner,
        participant_id: this.lastID
      })
    })
  })
})

app.get('/api/raffle/stats/:doll_id', (req, res) => {
  const doll_id = req.params.doll_id
  
  db.get("SELECT COUNT(*) as total_participants FROM raffle_participants WHERE doll_id = ?", [doll_id], (err, row) => {
    if (err) {
      res.status(500).json({ error: err.message })
      return
    }
    
    db.get("SELECT COUNT(*) as winners FROM raffle_participants WHERE doll_id = ? AND is_winner = 1", [doll_id], (err2, row2) => {
      if (err2) {
        res.status(500).json({ error: err2.message })
        return
      }
      
      res.json({
        total_participants: row.total_participants,
        winners: row2.winners,
        remaining_chances: 100 - row2.winners
      })
    })
  })
})

// 健康检查
app.get('/api/health', (req, res) => {
  res.json({ status: 'ok', timestamp: new Date().toISOString() })
})

// 启动服务器
app.listen(PORT, () => {
  console.log(`服务器运行在 http://localhost:${PORT}`)
  console.log('青花瓷娃娃平台已启动！')
})
